<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 教练管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-select v-model="select_status" placeholder="筛选教练" class="handle-select mr10" @change="getData">
                    <el-option key="1" label="已禁用教练" value="0"></el-option>
                    <el-option key="2" label="正常教练" value="-1"></el-option>
                </el-select>
                <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                <el-button type="primary" icon="el-icon-lx-add" @click="addCoachVisible=true">新增教练</el-button>
            </div>
            <el-table :data="coachData" border class="table" ref="multipleTable">
                <el-table-column type="index" label='序列' width="55" align="center"></el-table-column>
                <el-table-column label="头像" width="90" align="center">
                    <template slot-scope="scope">
                        <el-image style="width: 60px; height: 60px" fit="cover"
                            :src="`http://localhost/fitness/public/static/img/`+scope.row.avatar"
                            @click="handlePictureCardPreview(scope.row.avatar)">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="coachname" label="教练姓名" width="120">
                </el-table-column>
                <el-table-column prop="sex" label="性别" width="60">
                    <template slot-scope="scope">
                        {{scope.row.sex===1?'男':'女'}}
                    </template>
                </el-table-column>
                <el-table-column prop="cemail" label="邮箱地址" :formatter="formatter">
                </el-table-column>
                <el-table-column prop="area" label="教练(大师)领域" width="180">
                </el-table-column>                
                <el-table-column prop="ctel" label="电话" width="200">
                </el-table-column>
                <el-table-column prop="coachdate" label="从业年龄" width="160" align="center" sortable :formatter="coachdate">
                </el-table-column>
                <el-table-column prop="masterstatus" label="状态" width="120" align="center">
                    <template slot-scope="scope">
                        <template v-if="scope.row.masterstatus==1">
                            <i class="el-icon-circle-check" style="color:#1e90ff"> 普通教练</i>
                        </template>
                        <template v-if="scope.row.masterstatus==2">
                            <el-tooltip class="item" effect="dark" :content="scope.row.masterdate" placement="top">
                                <i class="el-icon-circle-check" style="color:#9b59b6"> 大师</i>
                            </el-tooltip>
                        </template>
                        <template v-if="scope.row.masterstatus==0">
                            <i class="el-icon-circle-close" style="color:red"> 不可用</i>
                        </template>
                        <template v-if="scope.row.masterstatus==3">
                            <el-tooltip class="item" effect="dark" :content="scope.row.masterdate" placement="top">
                                <i class="el-icon-magic-stick" style="color:#2ecc71"> 申请大师中</i>
                            </el-tooltip>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <template v-if="scope.row.masterstatus==1">
                            <el-button type="text" icon="el-icon-lx-hot" style="color:#9b59b6" @click="apply(scope.row)">申请大师</el-button>
                        </template>
                        <template v-if="scope.row.masterstatus==0">
                            <el-button type="text" icon="el-icon-circle-check" @click="onCoach(scope.row)">启用</el-button>
                            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                        </template>
                        <template v-else>
                            <el-button type="text" icon="el-icon-delete" class="red" @click="offCoach(scope.row)">禁用</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="25%">
            <el-form ref="editform" :rules="rules" :model="editform" label-width="80px">
                <el-form-item label="姓名" prop="coachname">
                    <el-input v-model="editform.coachname"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <div class="image-pre">
                        <span class="upload-m">     
                            <el-button type="primary" @click="editChoiceAvatar">上传
                                <i class="el-icon-upload el-icon--right"></i></el-button>
                            <input type="file" name="pic" id="editFile" class="el-upload__input" accept="image/*" 
                            ref="editfile" @change="editAvatar">
                        </span><br>
                        <div class="pre-view">
                            <img :src="editfile" alt="">                            
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="领域" prop="area">
                    <el-input v-model="editform.area"></el-input>
                </el-form-item>
                <el-form-item label="邮箱地址" prop="cemail">
                    <el-input v-model="editform.cemail"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 申请弹出框 -->
        <el-dialog title="申请" :visible.sync="applyVisible" width="30%">
            <el-form ref="form" label-width="80px">
                <el-form-item label="申请领域">
                    <el-input v-model="area"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="applyVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmApply">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加教练弹出框 -->
        <el-dialog title="新增教练" :visible.sync="addCoachVisible" width="30%">
            <el-form ref="addform" :rules="rules" :model="addform" label-width="80px">
                <el-form-item label="教练名" prop="coachname">
                    <el-input v-model="addform.coachname"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <div class="image-pre">
                        <span class="upload-m">
                            <el-button type="primary" @click="uploadAvatar">上传<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input type="file" name="pic" id="logoFile" class="el-upload__input" accept="image/*" 
                            ref="getfile" @change="getFile">
                        </span><br>
                        <div class="pre-view">
                            <img :src="file" alt="">                            
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="邮箱名" prop="cemail">
                    <el-input v-model="addform.cemail"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="ctel">
                    <el-input v-model="addform.ctel"></el-input>
                </el-form-item>
                <el-form-item label="领域" prop="area">
                    <el-input v-model="addform.area"></el-input>
                </el-form-item>
                <el-form-item label="教练时间" prop="coachdate">
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="addform.coachdate" style="width: 100%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addform.sex">
                        <el-radio label="男" value="1"></el-radio>
                        <el-radio label="女" value="0"></el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addCoachVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 禁用提示框 -->
        <el-dialog title="提示" :visible.sync="banVisible" width="300px" center>
            <div class="del-dialog-cnt">确认禁用？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="banVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmBan">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 启用提示框 -->
        <el-dialog title="提示" :visible.sync="onVisible" width="300px" center>
            <div class="del-dialog-cnt">确认启用？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="onVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmOn">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 预览图弹出框 -->
        <el-dialog :visible.sync="dialogImgVisible" width="25%">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
    import { fetchData } from '../api/index';
    export default {
        name: 'basetable',
        data() {
            var checkNum = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('电话不能为空'));
            }
            setTimeout(() => {
            if (!Number.isInteger(Number.parseInt(value))) {
                callback(new Error('请输入数字值'));
            } else {
                if (value.toString().length != 11) {
                    callback(new Error('号码必须为11位数'));
                } else {
                    callback();
                }
            }
            }, 500);
            };
            return {
                coachData: [],
                select_word: '',
                select_status: '-1',
                editVisible: false,
                banVisible: false,
                applyVisible: false,
                onVisible: false,
                editform: {},
                addCoachVisible: false,
                dialogImageUrl: '',
                dialogImgVisible: false,
                id: -1,
                area: '',
                addform: { },
                file: 'http://localhost/fitness/public/static/img/Snipaste_2019-07-22_10-59-50.png',
                editfile: 'http://localhost/fitness/public/static/img/Snipaste_2019-07-22_10-59-50.png',
                rules:{ 
                    ctel:[            
                        { required: true, validator: checkNum, trigger: 'blur' }
                    ],
                    coachname:[
                        { required: true, message: '请输入教练名字', trigger: 'blur' },
                        { min: 3, max: 11, message: '长度在 3 到  11 个字符', trigger: 'blur' }
                    ],
                    cemail:[
                        { required: true, type:'email', message: '请输入教练邮箱', trigger: 'blur' }
                    ],
                    area:[
                        { required: true, message: '请输入教练领域', trigger: 'blur' }
                    ],
                    coachdate:[
                        { required: 'date', message: '请选择日期', trigger: 'change' }
                    ],
                    sex:[
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ]
                }
            }
        },
        created() {
            this.getData();
        },
        methods: {
            // TODO: 此处clubid，你懂的
            getData() {
                this.$axios.get('/api/Club/clubCoachList',{
                    params: {
                        clubid: localStorage.clubid,
                        status: this.select_status
                    }
                }).then(res => {
                    this.coachData = res.data;
                })
            },
            search() {
                var _this = this;
                var promise1 = new Promise(function(resolve,reject){
                    // TODO: 这儿也有clubid
                    _this.$axios.get('/api/Club/clubCoachList',{
                        params: {
                            clubid: localStorage.clubid,
                            status: _this.select_status
                        }
                    }).then(res => {
                        _this.coachData = res.data;
                        resolve();
                    })
                    // _this.getData();
                    // resolve();
                });
                promise1.then((data)=>{
                    if(this.select_word==''){
                        this.getData();
                    } else {
                        this.coachData = this.coachData.filter((d) => {
                            if(d.coachname.indexOf(this.select_word) > -1){
                                return d;
                            }
                        })
                    }
                });
            },
            formatter(row, column) {
                return row.cemail;
            },
            coachdate(row, colum){
                if(row.coachdate == null){
                    return 0+'天';
                }
                let bt = row.coachdate;
                let begindate = new Date(bt.replace(/-/g,"/"));
                let enddate = new Date();
                let dateDiff = enddate.getTime() - begindate.getTime();
                let day = Math.floor(dateDiff / (24 * 3600 * 1000));
                return day+' 天 (约 '+(day/365).toFixed(1)+' 年)';
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            handleEdit(row) {
                this.editform = {
                    coachid: row.coachid,
                    coachname: row.coachname,
                    area: row.area,
                    cemail: row.cemail
                }
                if(row.avatar == null){
                    this.editfile = 'http://localhost/fitness/public/static/img/Snipaste_2019-07-22_10-59-50.png';
                }else{
                    this.editfile = 'http://localhost/fitness/public/static/img/'+row.avatar;
                }
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                this.$refs['editform'].validate((valid)=>{
                    if(valid){
                        let formData = new FormData();
                        for(let key in this.editform){
                            formData.append(key,this.editform[key])
                        }
                        if(this.$refs.editfile.files.length!=0){
                            formData.append('pic', this.$refs.editfile.files[0]);
                        }
                        let config = {headers: { 'Content-Type': 'multipart/form-data' }}
                        this.$axios.post('/api/Club/editClubCoach',formData,config).then(res => {
                            if(res.data == 1){
                                this.$message.success(`修改成功`);
                                this.getData();
                                this.editVisible = false;
                            } else if (res.data == 0) {
                                this.$message({
                                    message: '请修改一部分值',
                                    type: 'warning',
                                });
                            }
                        })
                    } else {
                        this.$message.error(`请完成表单`);
                    }
                })
            },
            onCoach(row){
                this.onVisible = true;
                this.id = row.coachid;
            },
            offCoach(row){
                this.banVisible = true;
                this.id = row.coachid;
            },
            // 确定禁用
            confirmBan(){
                this.$axios.get('/api/Club/banClubCoach',{
                    params: {
                        coachid: this.id
                    }
                }).then(res => {
                    if(res.data==1){
                        this.$message.success('删除成功');
                        this.banVisible = false;
                        this.getData();
                    }
                })

            },
            // 确定启用
            confirmOn(){
                this.$axios.get('/api/Club/onClubCoach',{
                    params: {
                        coachid: this.id
                    }
                }).then(res => {
                    if(res.data==1){
                        this.$message.success('启用成功');
                        this.onVisible = false;
                        this.getData();
                    }
                })

            },
            handlePictureCardPreview(url) {
                this.dialogImageUrl =`http://localhost/fitness/public/static/img/`+url;
                this.dialogImgVisible = true;
            },
            apply(row){
                this.applyVisible = true;
                this.area = row.area;
                this.id = row.coachid;
            },
            confirmApply(){
                this.$axios.get('/api/Club/coachToMaster',{
                    params: {
                        coachid: this.id,
                        area: this.area
                    }
                }).then(res => {
                    if(res.data == 1){
                        this.getData();
                        this.$message.success('申请成功');
                        this.applyVisible = false;
                    }
                })
            },
            confirmAdd(){
                this.$refs['addform'].validate((valid) => {
                    if (valid) {
                        console.log('object :', Number.isInteger(Number.parseInt(this.addform.ctel)));
                        this.addform.sex=="男"?this.addform.sex=1:this.addform.sex=0;
                        // TODO: 此处clubid也应该换成sessionid之类的
                        this.addform.clubid = localStorage.clubid;
                        let formData = new FormData();
                        for(let key in this.addform){
                            formData.append(key,this.addform[key])
                        }
                        if(this.$refs.getfile.files.length!=0){
                            formData.append('pic', this.$refs.getfile.files[0]);
                        }
                        let config = {headers: { 'Content-Type': 'multipart/form-data' }}
                        if(this.getHsonLength(this.addform)<7){
                            this.$message.error('请填写完表单');
                        } else {
                            this.$axios.post('/api/Club/addClubCoach',formData,config).then(res => {
                                if(res.data==1){
                                    this.addform = {};
                                    this.addCoachVisible = false;
                                    this.$message.success('添加成功');
                                    this.getData();
                                }
                            });
                        }
                    } else {
                        this.$message.error('请完成表单');
                    }
                });
            },
            uploadAvatar(){
                document.getElementById('logoFile').click();
            },
            getFile(){
                if(this.$refs.getfile.files.length == 0){
                    this.file = 'http://localhost/fitness/public/static/img/Snipaste_2019-07-22_10-59-50.png';
                }else{
                    this.file = this.$refs.getfile.files[0];
                    this.getImgBase();                    
                }
            },
            editAvatar(){
                if(this.$refs.editfile.files.length == 0){
                    this.editfile = 'http://localhost/fitness/public/static/img/Snipaste_2019-07-22_10-59-50.png';
                }else{
                    this.editfile = this.$refs.editfile.files[0];
                    this.geteditImgBase();                    
                }
            },
            getImgBase(){
                var _this = this;
                var file = this.$refs.getfile.files[0];
                var reader = new FileReader(); 
                //转base64
                reader.onload = function(e) {
                    _this.file = e.target.result;
                }
                reader.readAsDataURL(file);
            },
            geteditImgBase(){
                var _this = this;
                var editfile = this.$refs.editfile.files[0];
                var reader = new FileReader(); 
                //转base64
                reader.onload = function(e) {
                    _this.editfile = e.target.result;
                }
                reader.readAsDataURL(editfile);
            },
            editChoiceAvatar(){
                document.getElementById('editFile').click();
            },
            getHsonLength(json){
                var jsonLength=0;
                for (var i in json) {
                    jsonLength++;
                }
                return jsonLength;
            }
        }
    }

</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .table{
        width: 100%;
        font-size: 14px;
    }
    .red{
        color: #ff0000;
    }
    .mr10{
        margin-right: 10px;
    }
    .image-pre>.pre-view{
        height: 80px;
        width: 80px;
        overflow: hidden;
        margin-top: 20px;
        justify-content: center;
        justify-items: center;
        align-items: center;
        border-radius: 4px;
    }
    .pre-view>img{
        width: 80px;
        transform: scale(2.5);
    }
</style>
